package com.example.personnel.service;

import com.example.personnel.model.Personnel;
import com.example.personnel.repository.PersonnelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonnelService {
    @Autowired
    private PersonnelRepository personnelRepository;
    
    public Page<Personnel> searchPersonnel(String name, String position, String gender, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        List<Personnel> personnelList = personnelRepository.findByConditions(name, position, gender);
        
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), personnelList.size());
        
        return new org.springframework.data.domain.PageImpl<>(
            personnelList.subList(start, end),
            pageable,
            personnelList.size()
        );
    }
    
    public Personnel addPersonnel(Personnel personnel) {
        return personnelRepository.save(personnel);
    }
    
    public List<Personnel> searchPersonnel(String name, String position, String gender) {
        return personnelRepository.findByConditions(name, position, gender);
    }
    
    public Personnel updatePersonnel(Long id, Personnel personnel) {
        Personnel existingPersonnel = personnelRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("人员不存在"));
            
        existingPersonnel.setName(personnel.getName());
        existingPersonnel.setAge(personnel.getAge());
        existingPersonnel.setPosition(personnel.getPosition());
        existingPersonnel.setPhone(personnel.getPhone());
        existingPersonnel.setEmail(personnel.getEmail());
        existingPersonnel.setGender(personnel.getGender());
        
        return personnelRepository.save(existingPersonnel);
    }
    
    public void deletePersonnel(Long id) {
        personnelRepository.deleteById(id);
    }
} 